using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Ample.Model;

namespace Ample.Controls
{
   public partial class UserProfile : System.Web.UI.UserControl
   {
       private bool _isRegister = false;
       public bool IsRegister
       {
           get { return _isRegister; }
           set { _isRegister = value; }
       }

      private string _userName = "";
      public string UserName
      {
         get { return _userName; }
         set { _userName = value; }
      }

      private string _email= "";
      public string Email
      {
          get { return _email; }
          set { _email = value; }
      }

      protected void Page_Init(object sender, EventArgs e)
      {
         this.Page.RegisterRequiresControlState(this);
      }

      protected override void LoadControlState(object savedState)
      {
         object[] ctlState = (object[])savedState;
         base.LoadControlState(ctlState[0]);
         this.UserName = (string)ctlState[1];
      }

      protected override object SaveControlState()
      {
         object[] ctlState = new object[2];
         ctlState[0] = base.SaveControlState();
         ctlState[1] = this.UserName;
         return ctlState;
      }

      protected void Page_Load(object sender, EventArgs e)
      {
          if (!this.IsPostBack)
          {
              ddlSponsorCountry.DataSource = Helpers.GetCountries();
              ddlSponsorCountry.DataBind();

              ddlState.DataSource = Helpers.GetStates();
              ddlState.DataBind();

              ddlStateAlternative1.DataSource = Helpers.GetStates();
              ddlStateAlternative1.DataBind();

              ddlStateAlternative2.DataSource = Helpers.GetStates();
              ddlStateAlternative2.DataBind();

              // if the UserName property contains an emtpy string, retrieve the profile
              // for the current user, otherwise for the specified user

              if (!IsRegister)
              {
                  ProfileCommon profile = this.Profile;
                  if (!string.IsNullOrEmpty(UserName))
                  {
                      profile = this.Profile.GetProfile(this.UserName);
                      txtEmail.Text = Membership.GetUser(UserName).Email;

                      Model.UserProfile up = new BLL.User.UserBO().GetUserProfileByUsername(UserName);

                      if (up != null)
                      {
                          txtSponsorID.Text = up.SponsorID ?? "";
                          txtSponsorName.Text = up.SponsorName ?? "";
                          ddlSponsorCountry.SelectedValue = up.Country ?? "";
                      }
                  }

                  txtFirstName.Text = profile.FirstName;
                  txtLastName.Text = profile.LastName;
                  txtSSN.Text = profile.SSN;

                  txtPrimaryPhone.Text = profile.PrimaryPhone;
                  txtSecondaryPhone.Text = profile.SecondaryPhone;
                  txtAlternatePhone.Text = profile.AlternatePhone;
                  txtFax.Text = profile.Fax;

                  txtStreet.Text = profile.Address.Street;
                  txtCity.Text = profile.Address.City;
                  ddlState.SelectedValue = profile.Address.State;
                  txtPostalCode.Text = profile.Address.PostalCode;

                  txtStreetAlternative1.Text = profile.AddressAlternative1.Street;
                  txtCityAlternative1.Text = profile.AddressAlternative1.City;
                  ddlStateAlternative1.SelectedValue = profile.AddressAlternative1.State;
                  txtPostalCodeAlternative1.Text = profile.AddressAlternative1.PostalCode;

                  txtStreetAlternative2.Text = profile.AddressAlternative2.Street;
                  txtCityAlternative2.Text = profile.AddressAlternative2.City;
                  ddlStateAlternative2.SelectedValue = profile.AddressAlternative2.State;
                  txtPostalCodeAlternative2.Text = profile.AddressAlternative2.PostalCode;
              }
          }
      }

      public bool Save()
      {
          MembershipUser mu;
          MembershipCreateStatus mcs;

          try
          {
              // if the UserName property contains an emtpy string, save the current user's profile,
              // othwerwise save the profile for the specified user
              if (string.IsNullOrEmpty(UserName))
              {
                  Ample.DAL.CustomMembershipProvider provider = (Ample.DAL.CustomMembershipProvider)Membership.Providers["AmpleSqlMembershipProvider"];
                  string generatedPassword = Membership.GeneratePassword(12, 5);
                  mu = provider.CreateUser("", generatedPassword, txtEmail.Text, null, null, false, null, out mcs);

                  if (mcs == MembershipCreateStatus.Success)
                  {
                      Roles.AddUserToRole(mu.UserName, "Distributors");

                      this.UserName = mu.UserName;
                      this.Email = mu.Email;
                      SaveProfile();

                      Model.UserProfile userProfile = new Model.UserProfile
                      {
                          UserId = (Guid)mu.ProviderUserKey,
                          Country = ddlSponsorCountry.SelectedValue,
                          SponsorName = txtSponsorName.Text,
                          SponsorID = string.IsNullOrEmpty(txtSponsorID.Text) ? null : txtSponsorID.Text
                      };

                      new Ample.BLL.User.UserBO().SaveUserProfile(userProfile);
                      
                  }
                  else
                  {
                      this.UserName = string.Empty;
                      this.Email = string.Empty;

                      lblErrorMessage.Text = Helpers.ErrorCodeToString(mcs);

                      return false;
                  }
              }
              else
              {
                  mu = Membership.GetUser(UserName);

                  mu.Email = txtEmail.Text;
                  Membership.UpdateUser(mu);

                  SaveProfile();

                  Model.UserProfile userProfile = new Model.UserProfile
                  {
                      UserId = (Guid)mu.ProviderUserKey,
                      Country = ddlSponsorCountry.SelectedValue,
                      SponsorName = txtSponsorName.Text,
                      SponsorID = string.IsNullOrEmpty(txtSponsorID.Text) ? null : txtSponsorID.Text
                  };

                  new Ample.BLL.User.UserBO().SaveUserProfile(userProfile);
              }
          }
          catch (Exception ex)
          {
              Helpers.HandleProfileException(ex, ref lblErrorMessage);
              return false;
          }

          return true;
      }

       private void SaveProfile()
       {
           ProfileCommon profile = this.Profile;

           if(!string.IsNullOrEmpty(this.UserName))
            profile = this.Profile.GetProfile(this.UserName);
           
           profile.FirstName = txtFirstName.Text;
           profile.LastName = txtLastName.Text;
           profile.SSN = txtSSN.Text;

           profile.PrimaryPhone = txtPrimaryPhone.Text;
           profile.SecondaryPhone = txtSecondaryPhone.Text;
           profile.AlternatePhone = txtAlternatePhone.Text;
           profile.Fax = txtFax.Text;

           profile.Address.Street = txtStreet.Text;
           profile.Address.City = txtCity.Text;
           profile.Address.State = ddlState.SelectedValue;
           profile.Address.PostalCode = txtPostalCode.Text;

           profile.AddressAlternative1.Street = txtStreetAlternative1.Text;
           profile.AddressAlternative1.City = txtCityAlternative1.Text;
           profile.AddressAlternative1.State = ddlStateAlternative1.SelectedValue;
           profile.AddressAlternative1.PostalCode = txtPostalCodeAlternative1.Text;

           profile.AddressAlternative2.Street = txtStreetAlternative2.Text;
           profile.AddressAlternative2.City = txtCityAlternative2.Text;
           profile.AddressAlternative2.State = ddlStateAlternative2.SelectedValue;
           profile.AddressAlternative2.PostalCode = txtPostalCodeAlternative2.Text;
          
           profile.Save();
       }
   }
}